import React, {Component} from 'react';
import {createMaterialTopTabNavigator} from 'react-navigation-tabs';
import {createAppContainer} from 'react-navigation';
import {
  StyleSheet,
  View,
  Text,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import {connect} from 'react-redux';
import actions from '../action/index';
import NavigationUtil from '../navigator/NavigationUtil';
import NavigationBar from '../common/NavigationBar';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import PopularItem from '../common/PopularItem';
import TrendingItem from '../common/TrendingItem';
import Toast from 'react-native-easy-toast';
import {DeviceInfo} from 'react-native';
import {FLAG_STORAGE} from '../expand/dao/DataStore';
import FavoriteDao from '../expand/dao/FavoriteDao';
import FavoriteUtil from '../util/FavoriteUtil';
import EventBus from 'react-native-event-bus';
import EventTypes from '../util/EventTypes';

class FavoritePage extends Component {
  constructor(props) {
    super(props);
    this.tabNames = ['最热', '趋势'];
  }

  render() {
    const {theme} = this.props;
    let statusBar = {
      backgroundColor: theme.themeColor,
      barStyle: 'light-content',
    };
    let navigationBar = (
      <NavigationBar
        title={'收藏'}
        statusBar={statusBar}
        style={theme.styles.navBar}
      />
    );
    const TabNavigator = createAppContainer(
      createMaterialTopTabNavigator(
        {
          Popular: {
            screen: props => (
              <FavoriteTabPages
                {...props}
                flage={FLAG_STORAGE.flage_popular}
                theme={theme}
              />
            ),
            navigationOptions: {
              title: '最热',
            },
          },
          Trending: {
            screen: props => (
              <FavoriteTabPages
                {...props}
                theme={theme}
                flage={FLAG_STORAGE.flage_trending}
              />
            ),
            navigationOptions: {
              title: '趋势',
            },
          },
        },
        {
          tabBarOptions: {
            tabStyle: styles.tabStyle,
            upperCaseLabel: false, //是否使标签大写，默认为true
            scrollEnabled: false, //是否支持选项卡滚动，默认false
            style: {
              backgroundColor: theme.themeColor,
              // height: 30,
            },
            indicatorStyle: styles.indicatorStyle,
            labelStyle: styles.labelStyle,
          },
        },
      ),
    );

    return (
      <View
        style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 0 : 0}}>
        {navigationBar}
        <TabNavigator />
      </View>
    );
  }
}

const mapFavoriteStateToProps = state => ({
  theme: state.theme.theme,
});
const mapFavoriteDispatchToProps = dispatch => ({});
export default connect(
  mapFavoriteStateToProps,
  mapFavoriteDispatchToProps,
)(FavoritePage);

class FavoriteTab extends Component {
  constructor(props) {
    super(props);
    const {flage} = this.props;
    this.storeName = flage;
    this.favoriteDao = new FavoriteDao(flage);
  }
  componentDidMount() {
    this.loadData(true);
    EventBus.getInstance().addListener(
      EventTypes.bottom_tab_select,
      (this.listener = data => {
        if (data.to === 2) {
          this.loadData(false);
        }
      }),
    );
  }
  componentWillUnmount() {
    EventBus.getInstance().removeListener(this.listener);
  }

  loadData(isShowLoading) {
    const {onLoadFavoriteData} = this.props;
    onLoadFavoriteData(this.storeName, isShowLoading);
  }

  /**
   * 获取当前页面相关数据
   */
  _store() {
    const {favorite} = this.props;
    let store = favorite[this.storeName];
    if (!store) {
      store = {
        items: [],
        isLoading: false,
        projectModels: [], //要显示的数据
      };
    }
    return store;
  }

  onFavorite(items, isFavorite) {
    FavoriteUtil.onFavorite(
      this.favoriteDao,
      items,
      isFavorite,
      this.props.flage,
    );
    if (this.storeName === FLAG_STORAGE.flage_popular) {
      EventBus.getInstance().fireEvent(EventTypes.favorite_changed_popular);
    } else {
      EventBus.getInstance().fireEvent(EventTypes.favorite_changed_trending);
    }
  }
  renderItem(data) {
    const item = data.item;
    const {theme} = this.props;
    const Item =
      this.storeName === FLAG_STORAGE.flage_popular
        ? PopularItem
        : TrendingItem;
    return (
      <Item
        projectModel={item}
        theme={theme}
        onSelect={callback => {
          NavigationUtil.goPage(
            {
              theme,
              projectModes: item,
              favoriteDao: this.favoriteDao,
              callback,
            },
            'DetailPage',
          );
        }}
        onFavorite={(items, isFavorite) => this.onFavorite(items, isFavorite)}
      />
    );
  }

  render() {
    let store = this._store();
    const {theme} = this.props;
    return (
      <View style={styles.container}>
        <FlatList
          data={store.projectModels}
          renderItem={data => this.renderItem(data)}
          keyExtractor={item => '' + (item.item.id || item.item.fullName)}
          refreshControl={
            <RefreshControl
              title={'Loading'}
              titleColor={theme.themeColor}
              colors={[theme.themeColor]}
              refreshing={store.isLoading}
              onRefresh={() => this.loadData(true)}
              tintColor={theme.themeColor}
            />
          }
          onEndReached={() => {
            console.log('--onEndReached--');
            setTimeout(() => {
              if (this.canLoadMore) {
                this.loadData(true);
                this.canLoadMore = false;
              }
            }, 100);
          }}
          onEndReachedThreshold={0.5}
          onMomentumScrollBegin={() => {
            this.canLoadMore = true; //初始化滚动调用
            console.log('--onMomentumScrollBegin--');
          }}
        />
        <Toast ref={'toast'} position={'center'} />
      </View>
    );
  }
}

const mapStateToprops = state => ({
  favorite: state.favorite,
});

const mapDispatchToProps = dispatch => ({
  onLoadFavoriteData: (storeName, isShowLoading) =>
    dispatch(actions.onLoadFavoriteData(storeName, isShowLoading)),
  onThemeChange: theme => dispatch(actions.onThemeChange(theme)),
});

const FavoriteTabPages = connect(
  mapStateToprops,
  mapDispatchToProps,
)(FavoriteTab);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  tabStyle: {
    minWidth: 50,
    // padding: 0,
  },
  indicatorStyle: {
    height: 2,
    backgroundColor: 'white',
  },
  labelStyle: {
    fontSize: 13,
    marginTop: 6,
    marginBottom: 6,
    // margin: 0,
  },
  indicatorContainer: {
    alignItems: 'center',
  },
  indicator: {
    color: 'red',
    margin: 10,
  },
});
